package com.cmcc.aregister.ui.activity;

import java.util.HashMap;
import java.util.Map;
import com.cmcc.aregister.Controller;
import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.constant.GlobalSetting;
import com.cmcc.aregister.cs.http.HttpAsyncTask;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.unionPay.data.BindPay;
import com.unionPay.data.SaxHandler;
import com.unionPay.data.SaxParser;
import com.unionPay.net.HttpTask;
import com.unionPay.net.TaskExecutor;
import com.unionPay.utils.GlobalInfo;
import com.unionPay.utils.Utils;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class BindBankCardActivity extends ParentActivity
{
    private final static String TAG = "BindBankCardActivity";
    private Button bind_button, bool_button;
    private TextView view1;
    protected Controller mHttpManager = null;
    private String cardNumber = "";// 银行卡后四位
    private String bindId = "";// 绑定号
    private String userId = "";
    private String status = "";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        init(R.layout.p_bind_bankcard);
        super.onCreate(savedInstanceState);
    }

    public void init(int layoutId)
    {
        context = this;
        app = MyApplication.getInstance();
        mHttpManager = Controller.getInstance();
        mHttpManager.setCxt(this);
        setContentView(layoutId);
        setupView();
        setupData();
    }

    @Override
    protected void setupData()
    {
        if (getIntent().getParcelableExtra(Arguments.INTENT_TO_NEXT_PAGE) != null)
        {
            Map<String, Object> httpMap = ((PotoalParcelable) getIntent()
                .getParcelableExtra(Arguments.INTENT_TO_NEXT_PAGE)).map;
            cardNumber = (String) httpMap.get("cardNum");
            bindId = (String) httpMap.get("bindId");
            userId = (String) httpMap.get("userId");
            status = (String) httpMap.get("status");
            if (status.equals("1"))
            {
                view1.setVisibility(View.VISIBLE);
                view1.setText("绑定银行卡后四位：" + cardNumber);
                bool_button.setVisibility(View.VISIBLE);
            }
            else if (status.equals("-1"))
            {
                bind_button.setVisibility(View.VISIBLE);
            }
            else
            {
                showSingleAlertDlg(getString(R.string.notice), "访问服务器失败，请重试！",
                    getString(R.string.close));
            }
        }
    }

    protected void setupView()
    {
        view1 = (TextView) findViewById(R.id.txt);
        bind_button = (Button) findViewById(R.id.bind_bankcard);
        bool_button = (Button) findViewById(R.id.bool_bankcard);
        bind_button.setOnClickListener(onClickListener);
        bool_button.setOnClickListener(onClickListener);
    }

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v)
        {
            int id = v.getId();
            if (id == R.id.bind_bankcard)
            {
                addBankCard();
            }
            if (id == R.id.bool_bankcard)
            {
                // 解除绑定
                unBindCard();
            }
        }
    };

    private HttpAsyncTask boolCardTask;

    // 解除银联绑定
    private void unBindCard()
    {
        String params = "cid=8&token=wxcityMobileClient&mid=" + userId
            + "&mobile=" + ConfigUtilHelper.getMobile(app) + "&bind_id="
            + bindId + "&card_no=" + cardNumber;
        boolCardTask = new HttpAsyncTask(HttpAsyncTask.POST,
            GlobalSetting.XML_BOOL_BIND, Arguments.BOOL_BIND_URL, params,
            HttpAsyncTask.CACHE_TYPE_ACTION, true);
        boolCardTask.setUIHandler(boolCardHandler);
        showProgressDialogNew(R.string.dialog_loading_bool_bind);
        mHttpManager.execute(boolCardTask);
    }

    Handler boolCardHandler = new Handler() {
        public void handleMessage(Message msg)
        {
            logger.d("----------boolCardHandler----------");
            switch (msg.what)
            {
            case HttpAsyncTask.TASK_NOTIFY_RETURN_DATA:
                dismissProgressDialog();
                if (msg.obj != null)
                {
                    Map<String, Object> httpMap = (Map<String, Object>) msg.obj;
                    String status = (String) httpMap.get(Arguments.XML_STATUS);
                    String message = (String) httpMap
                        .get(Arguments.XML_MESSAGE);
                    if (Integer.parseInt(status) > 0)
                    {
                        showSingleAlertDlg(getString(R.string.notice), message,
                            getString(R.string.close));
                        bool_button.setVisibility(View.GONE);
                        view1.setVisibility(View.GONE);
                        bind_button.setVisibility(View.VISIBLE);
                    }
                }
                else
                {
                    showSingleAlertDlg(getString(R.string.notice), "解除绑定失败",
                        getString(R.string.close));
                }
                break;
            case HttpAsyncTask.TASK_NOTIFY_CONNECTION_FAIL:
                dismissProgressDialog();
                showSingleAlertDlg(getString(R.string.notice),
                    getString(R.string.read_fail), getString(R.string.close));
                break;
            }
        }
    };

    /**
     * 添加银行卡
     **/
    private void addBankCard()
    {
        new GetOrder().execute();
    }

    class GetOrder extends AsyncTask<String, Integer, BindPay>
    {
        @Override
        protected BindPay doInBackground(String... params)
        {
            GlobalInfo.merchantUserId = ConfigUtilHelper.getMobile(app);
            String content = Utils.toMGwXml(GlobalInfo.merchantId,
                Utils.getSendTime(), GlobalInfo.merchantOrderAmt,
                GlobalInfo.merchantUserId);
            try
            {
                content = Utils.encode(GlobalInfo.merchantId, content);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            TaskExecutor taskExecutor = new TaskExecutor();
            HttpTask httpTask = Utils.getHttpTask(GlobalInfo.REQUST_URL,
                content);
            GlobalInfo.currentHttpTask = httpTask;
            taskExecutor.execute(httpTask);
            int index = 0;

            while (GlobalInfo.netResult == null)
            {
                if (GlobalInfo.currentHttpTask == null)
                {
                    GlobalInfo.currentHttpTask = null;
                    return null;
                }
                try
                {
                    if (index > 30)
                    {
                        break;
                    }
                    index++;
                    Thread.sleep(1000);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

            if (GlobalInfo.netResult == null)
            {
                return null;
            }

            if (!Utils.decode(GlobalInfo.netResult))
            {
                GlobalInfo.netResult = null;
                return null;
            }

            SaxHandler saxHandler = (SaxHandler) SaxParser.parserxml(
                GlobalInfo.netResult, new SaxHandler());
            BindPay bindPay = saxHandler.getBinPay();
            GlobalInfo.netResult = null;
            return bindPay;
        }

        @Override
        protected void onPostExecute(BindPay result)
        {
            if (result == null)
            {
                Toast.makeText(BindBankCardActivity.this, "访问服务器失败，请重试！",
                    Toast.LENGTH_LONG).show();
            }
            else
            {
                if ("0000".equals(result.getRespCode()))
                {
                    GlobalInfo.bindpay = result;
                    com.bypay.utils.Utils.setPackageName("com.cmcc.aregister");
                    Intent intent = new Intent("yinlian_bindpay");
                    Bundle mBundle = new Bundle();
                    mBundle.putString("pkg", "unionPay_bind_back_more");
                    mBundle.putString("xml", getXml());
                    intent.putExtras(mBundle);
                    startActivityForResult(intent, 0000);
                }
                else
                {
                    Toast.makeText(BindBankCardActivity.this,
                        result.getRespDesc(), Toast.LENGTH_LONG).show();
                }
            }
            super.onPostExecute(result);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1 && data != null)
        {
            SaxHandler saxHandler = (SaxHandler) SaxParser.parserxml(
                data.getStringExtra("xml"), new SaxHandler());
            BindPay bindPay = saxHandler.getBinPay();
            cardNumber = bindPay.getCardNum();
            if (GlobalInfo.result.equals(bindPay.getRespDesc())
                && "0000".equals(bindPay.getRespCode()))
            {
                bind_button.setVisibility(View.GONE);
                bool_button.setVisibility(View.VISIBLE);
                view1.setVisibility(View.VISIBLE);
                view1.setText("绑定银行卡后四位：" + cardNumber);
            }
        }
    }

    @Override
    protected void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    protected void onPause()
    {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onRestart()
    {
        // TODO Auto-generated method stub
        super.onRestart();
    }

    @Override
    protected void onStop()
    {
        // TODO Auto-generated method stub
        super.onStop();
    }

    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
    }

}
